﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 企业人事管理系统
{
    public partial class ContractForm : DataListForm
    {
        private static string sql = string.Format("select * from {0}", DataName.contractTable);
        private static string title = "合同信息管理";

        private DataGridViewCellCancelEventHandler beginEvent;
        private OpenFileDialog PathDialog;
        private EventHandler openFileCilck;
        private ToolStripMenuItem openFileItem;

        public static ContractForm getDefaultForm()
        {
            ContractForm form = new ContractForm(title, sql);
            return form;
        }


        public ContractForm(string t,string s):base(t,s)
        {
            InitializeComponent();
            this.Text = title;

            PathDialog = new OpenFileDialog();
            openFileItem = new ToolStripMenuItem("查看该合同");
            contextMenuDataShow.Items.Add(openFileItem);
            addEvent();
        }

        private void addEvent()
        {
            beginEvent = new DataGridViewCellCancelEventHandler(cellBeginEdit);
            dataShow.CellBeginEdit += beginEvent;

            openFileCilck = new EventHandler(FileClick);
            openFileItem.Click += openFileCilck;
        }

        private void cellBeginEdit(object sender, EventArgs e)
        {
            DataGridViewCell cell = dataShow.CurrentCell;

            int index = getColIndex(DataName.contractPath);

           if (cell.ColumnIndex == index)
           {
                MessageBox.Show("请选择您的合同文件");
                PathDialog.Title = "选择合同文件";
                PathDialog.InitialDirectory = cell.Value.ToString();
                PathDialog.ShowDialog();
                cell.Value = PathDialog.FileName;
                PathDialog.FileName = "";
           }
        }

        private void FileClick(object sender, EventArgs e)
        {
            int index = getColIndex(DataName.contractPath);
            string path = dataShow.CurrentRow.Cells[index].Value.ToString();
            try
            {
                System.Diagnostics.Process.Start(path);
            }catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
           
        }

        private int getColIndex(string headerText)
        {
            int index = 0;
            for (index = 0; index < dataShow.Columns.Count; index++)
            {
                if (dataShow.Columns[index].HeaderText.Equals(headerText))
                {
                    break;
                }
            }
            return index;
        }
    }
}
